<template>
	<view>
		<common-title :title="titleContent" @clickLeft="backToUpPage"></common-title>
		<!-- 菜单页面 -->
		<view class="dish-menu-container">
			<!-- 菜品类别 -->
			<scroll-view class="dish-menu-left" scroll-y>
				<view class="dish-menu-categories">
					<view class="dish-menu-categor" 
					v-for="(category, index) in categories" 
					@click="selectCategory(category)" 
					:class="{ active: selectedCategory.id === category.id }" 
					:key="category.id" >
						{{category.categoryName}}
					</view>
				</view>
			</scroll-view>
			
			<!-- 菜品列表 -->
			<scroll-view @scrolltoupper="selectFirstCategory" @scroll="changeCategory" class="dish-menu-right" scroll-y :scroll-into-view="scrollIntoViewId" scroll-with-animation v-if="dishes.length">
				<view class="dish-menu-dishes" v-for="category in categories" :key="category.id" :id="'category_'+category.id">
						<uni-section class="dish-menu-dishes-section" :title="categoryName(category.id)">
							<template v-slot:decoration>
								<view class="dish-menu-dishes-section-decoration"></view>
							</template>
							<view class="" v-for="dish in dishes" :key="dish.id">
								<view v-if="dish.categoryId === category.id">
									<uni-card class="dish-menu-dish" >
										<view class="dish-meun-dish-image"><image :src="dish.dishImage" mode="aspectFill"></image></view>
										<view class="dish-menu-dish-name">{{dish.dishName}}</view>
										<view class="dish-menu-dish-ingredients">{{dish.description}}</view>
										<view class="dish-menu-dish-bottom">
											<view class="dish-menu-dish-price">
												{{dish.price}}<uni-icons type="heart-filled" color="#ff4500" size="36rpx" style="margin-left: 5rpx;"></uni-icons>
												<text class="dish-menu-dish-price-mount">/份</text>
											</view>
											<view class="dish-menu-dish-select">
												
												
												<!-- 当数量为 0 时才显示此加号 -->
												<view v-if="dish.quantity === 0" class="dish-menu-dish--select-add-or-dec" @click="addDishQuantity(dish)">
													<uni-icons type="plus-filled" color="#ff6f50" size="45rpx"></uni-icons>
												</view>
												
												<!-- 初始渲染时显示加号 -->
												<view v-else  class="dish-menu-dish--select-add-or-dec">
													<uni-icons type="minus-filled" color="#ff6f50" @click="decDishQuantity(dish)" size="45rpx"></uni-icons>
													<text style="font-size: 32rpx; padding-left: 10rpx; padding-right: 10rpx;">{{ dish.quantity }}</text> <!-- 显示数量 -->
													<uni-icons type="plus-filled" color="#ff6f50" @click="addDishQuantity(dish)" size="45rpx"></uni-icons>
												</view>
											</view>
										</view>
									</uni-card>
								</view>
								
							</view>
						</uni-section>
					</view>
			</scroll-view>
		
			<!-- 底部框框 -->
			<view class="dish-menu-bottom">
				<!-- 底部购物车栏 -->
				<view class="dish-menu-bottom-cart">
					<!-- 购物车图标 -->
					<view class="dish-menu-bottom-cart-icon" :class="{active : cartDish.length > 0}" @click="cartDish.length > 0 ? popupCart() : null">
						<uni-badge class="dish-menu-bottom-cart-count" size="normal" :text="cartDish.length" absolute="rightTop" :customStyle="{background: '#ff4500'}">
							<uni-icons  type="cart" color="" size="80rpx"></uni-icons>
						</uni-badge>
					</view>
					<!-- 总价格 -->
					<view class="dish-menu-bottom-cart-amount">
						<uni-icons class="dish-menu-bottom-cart-amount-color" :class="{active : cartDish.length > 0}"  type="heart-filled" color="" size="36rpx" style="margin-left: 5rpx;"></uni-icons>{{cartDishCountPrice}}
					</view>
				</view>
				<!-- 去结算 -->
				<view class="dish-menu-bottom-ordered" :class="{active : cartDish.length > 0}" @click="goToDishOrder">
					点好了
				</view>
			</view>
			
			
			<!-- 购物车弹窗 -->
			<uni-popup style="z-index: 8;" ref="cartDishPopup">
				
				<view class="cart-popup-content">
					<!-- 弹窗头部 -->
					<view class="cart-popup-content-head">
						<view style="font-size: 36rpx; margin-left: 30rpx;">已选商品</view>
						<view style="font-size: 26rpx; margin-right: 30rpx;" @click="clearnCart"><uni-icons type="trash" size="26rpx"></uni-icons>清空</view>
					</view>
					<!-- 购物车中的菜品 -->
					<scroll-view class="cart-popup-content-scroll"  :scroll-y="true" >
						<view class="cart-popup-content-dishes" v-for="(item,index) in cartDish" :key="index">
							<!-- 购物车中的菜品信息 -->
							<view class="cart-popup-content-dish-image-info">
								<image :src="item.dishImage" mode="aspectFill"></image>
								<view class="cart-popup-content-dish-info">
									<view class="cart-popup-content-dish-info-name">{{item.dishName}}</view>
									<view class="cart-popup-content-dish-info-price">{{item.price * item.quantity}}<uni-icons type="heart-filled" color="#ff4500" size="36rpx" style="margin-left: 5rpx;" /></view>
								</view>
							</view>
							<!-- 对购物车中的菜品进行增减操作 -->
							<view class="cart-popup-content-dishes-operation">
								<uni-icons type="minus-filled" color="#ff6f50" @click="decCartDish(item)" size="45rpx"></uni-icons>
								<text style="font-size: 32rpx; padding-left: 10rpx; padding-right: 10rpx;">{{ item.quantity }}</text> <!-- 显示数量 -->
								<uni-icons type="plus-filled" color="#ff6f50" @click="addCartDish(item)" size="45rpx"></uni-icons>
							</view>
						</view>
					</scroll-view>
				</view>
			</uni-popup>
			
			
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted } from 'vue';
	import { apiGetRestaurantCategoriesByStatus, apiGetRestaurantDishesByStatus } from '@/utils/apiRestaurant.js';
	import { setDataToStorage, getDataFromStorage, sleep } from '@/utils/commonUtils';
	//================================common-title=========================================
	//标题内容
	const titleContent = ref({
		left:'',
		midst:'猪小妹餐厅'
	});
	
	//返回
	const backToUpPage = () => {
		uni.switchTab({
			url:'/pages/index/index'
		})
	};
	
	// 定义响应式变量
	const categories = ref([]);
	
	
	// 获取菜品类别的异步函数
	const getRestaurantCategories = async () => {
	    let res = await apiGetRestaurantCategoriesByStatus(1); // 调用 API 函数
	    if (Array.isArray(res) && res.length > 0) {
	    	categories.value = res; // 确保是数组且非空
	    	selectedCategory.value = categories.value[0];
	    } else {
	    	categories.value = [];
	    }
	};
	
	getRestaurantCategories(); // 调用获取菜品类别的函数
	
	
	// 右侧菜品对应的标题头的id
	const scrollIntoViewId = ref('');
	
	// 总菜品信息
	const dishes = ref([]);
	
	
	
	// 购物车中的菜品
	const cartDish = ref([]);
	
	// 获取菜品信息
	const fetchDishes = async () => {
			let res = await apiGetRestaurantDishesByStatus(1);
			if (Array.isArray(res) && res.length > 0){
				dishes.value = res;
			}else{
				dishes.value = [];
			}
			// 初始化数量
			// 更新 quantity
			dishes.value.forEach(dish => {
				// 如果 cartDish 中有对应的 dish.id，则设置 quantity 为 cartDish 中的值
				if (cartDish.value[dish.id] !== undefined) {
					dish.quantity = cartDish.value[dish.id].quantity;
				} else {
					dish.quantity = 0; // 如果没有对应的值，可以选择保留为 0
				}
			});
			
	};
	
	const categoryName = (categoryId) => {
	    const category = categories.value.find(cat => cat.id === categoryId);
	    return category ? category.categoryName : '未找到分类'; // 如果没有找到分类，返回提示信息
	};
	
	// 设置被选中的菜品目录，默认为第一个
	const selectedCategory = ref({});
	
	// 选择菜品
	const selectCategory = (category) => {
		selectedCategory.value = category;
		scrollIntoViewId.value = 'category_'+category.id;
	};
	
	
	// 添加菜品数量
	const addDishQuantity = (dish) => {
		dish.quantity += 1;
		addCartDish(dish);
		// console.log(cartDish.value)
	};
	
	// 减少菜品数量
	const decDishQuantity = (dish) => {
		dish.quantity -=1;
		decCartDish(dish);
	};
	
	// 菜品在购物车中增加
	const addCartDish = (dish) => {
		const foundItem = cartDish.value.find(item => item.id === dish.id);
		
		if (foundItem) {
				foundItem.quantity += 1;
		} else {
				const newItem = { ...dish, quantity: 1 };
				cartDish.value.push(newItem);
		}
		
		// 同步更新 dishes 中的数量
		const filteredItem = dishes.value.find(item => item.id === dish.id);
		if (filteredItem) {
			filteredItem.quantity = foundItem ? foundItem.quantity : 1; // 设置对应的数量
		}
		setDataToStorage('cartDishData', cartDish);
	};
	
	// 菜品在购物车中减少
	const decCartDish = (dish) => {
		const foundItem = cartDish.value.find(item => item.id === dish.id);
		
		if (foundItem) {
				foundItem.quantity -= 1;
				
				if (foundItem.quantity <= 0) {
				  cartDish.value = cartDish.value.filter(item => item.id !== dish.id);
				}
		}
		
		// 同步更新 dishes 中的数量
		const filteredItem = dishes.value.find(item => item.id === dish.id);
		if (filteredItem) {
			filteredItem.quantity = foundItem ? foundItem.quantity : 0; // 更新对应的数量
		}
		setDataToStorage('cartDishData', cartDish);
	};
	
	// 计算购物车总价格
	const cartDishCountPrice = computed(() => {
	  return cartDish.value.reduce((total, item) => total + item.price * item.quantity, 0);
	});
	
	// 滑动菜品触底切换菜品类别	
	const changeCategory = (event) => {
	  const scrollTop = event.detail.scrollTop; // 获取当前滚动距离
	
	  categories.value.forEach(category => {
	    const categoryId = 'category_' + category.id;
	
	    // 使用 uni.createSelectorQuery() 来选择元素
	    uni.createSelectorQuery()
	      .select('#' + categoryId)
	      .boundingClientRect(data => {
	        if (data) {
	          const { top, height } = data; // 获取元素的顶部和高度
	          
	          // 仅当顶部在视口内且底部未完全出视口
	          const inViewport = (top <= 100 && top + height >= 200);
	          
	          if (inViewport) {
	            selectedCategory.value = category; // 更新选中的分类
	          }
	        }
	      })
	      .exec(); // 执行查询
	  });
	};
	
	// 滑动菜品触顶切换到第一个类别
	const selectFirstCategory = (event) => {
		selectedCategory.value = categories.value[0];
		scrollIntoViewId.value = 'category_'+categories.value[0].id;
	}
	
	// 
	const cartDishPopup = ref(null);
	
	// 点击购物车后弹出购物车
	const popupCart = () => {
		// console.log('11');
		cartDishPopup.value.open("bottom");
		
	};
	
	// 点击清空后清空购物车
	const clearnCart = () => {
		cartDish.value = [];
		// 初始化数量为 0
		dishes.value.forEach(dish => {
			dish.quantity = 0; 
		});
		setDataToStorage('cartDishData', cartDish);
	};
	
	// 点好了，跳转到dish-order页面
	const goToDishOrder = () => {
		
		try {
			if (!Array.isArray(cartDish.value)) {
			  console.error("Cart is not an array:", cartDish.value);
			  return;
			}
			// setDataToStorage('cartDishData', cartDish);
			uni.redirectTo({
			  url: `/pages/index/restaurant/restaurant-order` // 确保路径正确
			}).catch(err => {
			  console.error("Navigation error:", err); // 捕获任何导航错误
			});
		} catch (e) {
			// error
		}
		
	};
	
	
	
	
	onMounted(async () => {
	    try {
			if (Array.isArray(cartDish.value) && cartDish.value.length === 0) {
			    cartDish.value = await getDataFromStorage('cartDishData'); // 等待获取数据并赋值
			} else {
			    cartDish.value = [];
			}
			// console.log(cartDish.value);
	    } catch (error) {
			cartDish.value = [];
	    } finally {
			await sleep(10);  // 等待2000毫秒
			fetchDishes();
		}
	});
	
	
	
</script>


<style lang="scss" scoped>
	.dish-menu-container {
		display: flex;
		.dish-menu-left {
			width: 200rpx;
			align-items: center;
			height: calc(100vh - 120px);
			background-color: #f8f8f8; // 背景色
			.dish-menu-categor {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 200rpx;
				height: 112.5rpx;
				cursor: pointer; // 鼠标指针样式
				border-radius: 4rpx; // 圆角
				font-size: 32rpx;
			
				&.active {
					width: 200rpx;
					background-color: $brand-theme-color; // 活动状态背景色
					color: #fff; // 活动状态字体颜色
					font-weight: 600;
					padding-left: 45rpx;
				}
			}
		}
		
		.dish-menu-right {
			width: 550rpx;
			height: calc(100vh - 140px);
			// padding-bottom: 120rpx;
			.dish-menu-dishes {
				.dish-menu-dishes-section {
					.dish-menu-dishes-section-decoration {
						width: 5rpx;
						height: 30rpx;
						border-radius: 5rpx;
						margin-right: 14rpx;
						background-color: $brand-theme-color;
					}
				}
				
			
				.dish-menu-dish {
					margin-bottom: 20rpx; // 菜品间距
					border: 1rpx solid #ddd; // 边框
					border-radius: 4rpx; // 圆角
					overflow: hidden;
					display: flex;
					align-items: center;
					justify-content: center;
			
					.dish-meun-dish-image {
						width: 400rpx; // 图片宽度
						height: 300rpx; // 高度
						overflow: hidden; // 隐藏超出部分
			
						image {
							width: 100%; // 图片宽度
							height: 100%; // 图片高度
							object-fit: cover; // 图片覆盖
						}
					}
			
					.dish-menu-dish-name {
						font-size: 36rpx; // 菜品名称字体大小
						font-weight: bold; // 加粗
						padding: 10rpx; // 内边距
					}
			
					.dish-menu-dish-ingredients {
						font-size: 24rpx;
						color: #777; // 食材描述颜色
						padding: 0 10rpx; // 内边距
					}
			
					.dish-menu-dish-bottom {
						display: flex; // Flexbox 布局
						justify-content: space-between; // 两端对齐
						align-items: center;
						padding: 10rpx; // 内边距
			
						.dish-menu-dish-price {
							font-size: 36rpx; // 价格字体大小
							color: #333; // 价格文本颜色
							.dish-menu-dish-price-mount{
								font-size: 22rpx;
								color: #333;
							}
						}
			
						.dish-menu-dish-select {
							// 选择按钮或图标样式
							cursor: pointer; // 鼠标指针样式
							.dish-menu-dish--select-add-or-dec{
								display: flex;
								align-items: center;
							}
						}
					}
				}
				
			}
		}
		
		.dish-menu-bottom {
			width: 100%;
			height: 120rpx;
			position: fixed;
			z-index: 10;
			display: flex;
			// justify-content: center;
			align-items: center;
			bottom: 0rpx;
			background-color: #fff;
			.dish-menu-bottom-cart {
				display: flex;
				align-items: center;
				.dish-menu-bottom-cart-icon {
					color: #a7a7a7;
					position: relative;
					left: 50rpx;
					margin-right: 100rpx;
					&.active {
						color: #ff6f50;
					}
				}
				.dish-menu-bottom-cart-amount {
					font-size: 36rpx;
					display: flex;
					align-items: flex-end;
					.dish-menu-bottom-cart-amount-color {
						color: #a7a7a7;
						&.active {
							color: #ff4500;
						}
					}
				}
				
			}
			
			.dish-menu-bottom-ordered {
				width: 200rpx;
				height: 100rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 100rpx;
				color: #fff;
				font-size: 36rpx;
				font-weight: bold;
				background-color: #a7a7a7;
				position: absolute;
				right: 60rpx;
				&.active {
					background-color: #ff6f50;
				}
				
			}
		}
	
		
		
		.cart-popup-content {
			background-color: #fff;
			margin-bottom: 110rpx;
			padding: 30rpx 0;
			width: 750rpx;
			border-radius: 10rpx 10rpx 0 0;
			.cart-popup-content-head {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
			
			.cart-popup-content-scroll {
				max-height: 800rpx;
				.cart-popup-content-dishes {
					width: 100%;
					height: 200rpx;
					padding-top: 20rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					.cart-popup-content-dish-image-info {
						// width: 20rpx;
						display: flex;
						align-items: center;
						height: 200rpx;
						image{
							width: 200rpx;
							height: 150rpx;
							border-radius: 20rpx;
							margin-left: 30rpx;
						}
						.cart-popup-content-dish-info {
							padding-left: 30rpx;
							font-size: 36rpx;
							.cart-popup-content-dish-info-name {
								padding-bottom: 50rpx;
							}
							.cart-popup-content-dish-info-price {
								
							}
						}
					}
					
					.cart-popup-content-dishes-operation {
						// flex: 1;
						padding-right: 20rpx;
						font-size: 36rpx;
					}
				}
			}
			
			
		}
		
	}
</style>
